<template>
	<el-form-item :prop="prop" :label="label">
		<el-select-v2 v-bind="$attrs" :options="curOptions" :disabled="!isEdit" :filter-method="filterMethod" filterable
			clearable :placeholder="placeholder" :style="inputStyle" />
	</el-form-item>
</template>

<script lang="ts" setup>
// 基础资料下拉选择框, 自带缓存, 第一次调用后, 会缓存下来, 下次调用时, 直接从缓存中获取
// 非基础资料不适合缓存, 不用使用此方法
/* 用法
<MkSelectBasEntity label='项目类型' v-model='ctx.entity.xiangMuLeiXing' prop='xiangMuLeiXing' :isEdit='ctx.isEdit' entity="BasXueYeLaiYuan" />
*/
import { ref } from 'vue'
import { getInputWidth, filterArrayWithPinYin } from './shared';
import { getXieYiYiYuanList4Select, xueYePinZhongList, getBasXueYeChanPinFeiYongList } from '/@/stores/baseInfo/';
import { getBasXueYeLaiYuanList } from '/@/stores/baseInfo/';

defineOptions({
	name: 'MkSelectBasEntity'
})

const props = defineProps({
	prop: {
		type: String,
	},
	label: {
		type: String,
	},
	entity: { // 实体名, 数据库表名
		type: String,
		require: true
	},
	isEdit: {
		type: Boolean,
		default: true
	},
	// 占位符用props传入，默认空字符串，不显示“请选择”
	placeholder: {
		type: String,
		default: ''
	},
	col: { // 控制宽度, 最多设置为3, 特殊情况可以设置为4
		type: Number,
		default: 1
	},
})

// 过滤后的数据源 
const curOptions = ref<BasEntityType[]>([])
let options = [] as any[]

const { inputStyle } = getInputWidth(props.col);

onMounted(async () => {
	if (!props.entity) {
		return;
	}
	let list = [] as BasEntityType[];
	// 获取基础资料列表,需要缓存
	switch (props.entity) {
		case 'XieYiYiYuan': // 协议医院
			list = getXieYiYiYuanList4Select();
			break;
		case 'BasXueYePinZhong': // 血液品种
			list = xueYePinZhongList.value
			break;
		case 'BasXueYeChanPinFeiYong': // 血液产品费用
			list = await getBasXueYeChanPinFeiYongList()
			break;
		case 'BasXueYeLaiYuan': // 血液来源
			list = await getBasXueYeLaiYuanList()
			break;
	}
	options = list.map((item, idx) => ({
		value: item.id,
		label: item.mingCheng,
		disabled: !item.isEnabled,
	}))
	// 触发界面渲染
	filterMethod("")
})

// 根据中文拼音过滤
const filterMethod = (query: string) => {
	curOptions.value = filterArrayWithPinYin(options, query);
}
</script>